<?php

namespace App\HttpController\Admin;

use App\Model\CatesModel;
use EasySwoole\Validate\Validate;

class CateController extends AuthController {

    public function index(){
        $model  = new CatesModel();
        $list   = $model->get();
        return $this->writeJson(0,$list);
    }

    public function update(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $model = new CatesModel();
        $validate = new Validate();
        $validate->addColumn('name')->required('请填写维修类别名称')->func(function () use($data,$model){
            return empty($model->where('name',$data['name'])->first());
        },'类别名称已存在');
        if($this->validate($validate)){
            if($data['id']){
                $model->update($data);
                return $this->writeJson(0,null,'编辑维修类别信息成功');
            }else{
                //新增
                $id = $model->create($data);
                return $this->writeJson(0,['id'=>$id],'新增维修类别信息成功');
            }
        }else{
            return $this->writeJson(1, null, $validate->getError()->__toString());
        }
    }

    public function destroy(){
        $request = $this->request();
        $id = (int)$request->getRequestParam('id');
        if(!$id){
            return $this->writeJson(1,null,'参数错误');
        }
        $model = new CatesModel();
        $model->destroy($id);
        return $this->writeJson(0);
    }

}
